package com.sjs.boot.dynamic.facade.run;

import com.sjs.boot.dynamic.core.config.method.MethodConfig;
import com.sjs.boot.dynamic.core.config.method.parameter.ParameterInfo;
import com.sjs.boot.dynamic.core.run.MethodContext;
import com.sjs.boot.dynamic.facade.config.AbstractRequestConfig;
import com.sjs.boot.dynamic.protocol.RetCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/9 19:28
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
public abstract class AbstractRequester extends AbstractHandler {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractRequester.class);

    abstract protected int buildParas(MethodContext context, Map<String, Object> reqParameters);


    public int buildParameters(MethodContext context, Map<String, Object> reqParameters) {
        int retCode = buildParas(context, reqParameters);
        if (retCode != RetCode.OK.getCode()) {
            LOG.debug("Fail to get perameters from request, retCode={}", retCode);
            return retCode;
        }
        return RetCode.OK.getCode();
    }


    public int checkRequest(MethodContext context) {
        MethodConfig mc = context.getMethodConfig();
        AbstractRequestConfig rc = mc.getRequestConfig();
        int retCode = RetCode.OK.getCode();
        Object v;

        int sn = 1;
        for (ParameterInfo pi : rc.getParameters()) {
            v = pi.getValue(context); //必须先调用getValue，否则系统参数类型可能不在请求参数中
            if (!pi.check(context, v)) {
                retCode = context.getResultCode();
                if (retCode == RetCode.OK.getCode()) {
                    retCode = pi.getWrongCode(sn);
                    //约定返回码-RetCode.WRONG_PARAMETER为第N个参数错误，也可以通过配置制定返回码
                    context.setResult(retCode, "parameter(" + pi.getName() + ") error:" + pi.getClaim());
                }
                break;
            }

            sn++;
        }

        return retCode;
    }
}
